//
//  NewCellManager.m
//  suRead
//
//  Created by lidi on 2018/1/30.
//  Copyright © 2018年 bao. All rights reserved.
//

#import "NewCellManager.h"

#import "NewsOneOfImageCell.h"
#import "ZhuanTiCell.h"
#import "NewsQuestionCell.h"
#import "VideoShowCell.h"

#import "NewsAdvCell.h"

#import "M_News.h"
#import "NewsCell.h"
#import "NewsImageCell.h"

#import "NewsZTCell.h"
#import "NewsWordCell.h"
#import "NewsCTCell.h"
#import "NewsDTCell.h"

#import "WenBaDetailController.h"
#import "NewsAlbumViewController.h"
#import "NewsWebViewController.h"
#import "SpecialNewsListViewController.h"
#import "NewsDetailViewController.h"
#import "WenBaTagListController.h"

#import "ServiceNews.h"
#import "UIViewController+HUD.h"
#import "M_PlayNewsDetail.h"
#import "AccountManager.h"
#import <RongIMLib/RongIMLib.h>
#import "RCDLiveChatRoomViewController.h"
#import "RCDLiveChatRoomLSViewController.h"
#import "RCDLiveKitCommonDefine.h"
#import "AFNetworking.h"
#import <CommonCrypto/CommonDigest.h>
#import "AppDelegate.h"
#import "RCDLive.h"
#import "ServiceUserNew.h"

@interface NewCellManager()
@property(nonatomic,strong)NSMutableArray *readHistory;
@end

@implementation NewCellManager

static NewCellManager *_instance;

+ (instancetype)shared {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [NewCellManager new];
        NSArray *his = [[NSUserDefaults standardUserDefaults] objectForKey:@"NewsReadHistory"];
        if ([his isKindOfClass:[NSArray class]] && [his count] > 0) {
            _instance.readHistory = [NSMutableArray arrayWithArray:his];
        } else {
            _instance.readHistory = [NSMutableArray array];
        }
    });
    return _instance;
}

- (BOOL)hasRead:(NSString *)newsId {
    return [self.readHistory containsObject:newsId];
}

- (void)saveReadHistory:(NSString *)newsId {
    if (![self.readHistory containsObject:newsId]) {
        [self.readHistory addObject:newsId];
        [[NSUserDefaults standardUserDefaults] setObject:self.readHistory forKey:@"NewsReadHistory"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

+ (void)registerCellFor:(UITableView *)tableView {
    
    [tableView registerNib:[UINib nibWithNibName:@"NewFocusNewsCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewFocusNewsCell"];
    [tableView registerNib:[UINib nibWithNibName:@"NewFocusWordCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewFocusWordCell"];
    [tableView registerNib:[UINib nibWithNibName:@"NewsFocusImageCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsFocusImageCell"];
    [tableView registerNib:[UINib nibWithNibName:@"NewsFocusCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsFocusCell"];
    [tableView registerNib:[UINib nibWithNibName:@"NewsCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsCell"];
    [tableView registerNib:[UINib nibWithNibName:@"NewsAdvCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsAdvCell"];
    [tableView registerNib:[UINib nibWithNibName:@"NewsImageCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsImageCell"];
    [tableView registerNib:[UINib nibWithNibName:@"NewsOneOfImageCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsOneOfImageCell"];
    [tableView registerNib:[UINib nibWithNibName:@"NewsQuestionCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsQuestionCell"];
    [tableView registerNib:[UINib nibWithNibName:@"ZhuanTiCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"ZhuanTiCell"];
    [tableView registerNib:[UINib nibWithNibName:@"VideoShowCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"VideoShowCell"];
    
    [tableView registerNib:[UINib nibWithNibName:@"NewsZTCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsZTCell"];
    [tableView registerNib:[UINib nibWithNibName:@"NewsWordCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsWordCell"];
    [tableView registerNib:[UINib nibWithNibName:@"NewsCTCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsCTCell"];
    [tableView registerNib:[UINib nibWithNibName:@"NewsDTCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsDTCell"];
}

+ (UITableViewCell *)cellForNews:(M_News *)news whos:(NSInteger)whos tableView:(UITableView *)tableView {
    
    switch (whos) {
        case 1: {
            //特殊新闻
            NewsOneOfImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsOneOfImageCell"];
            cell.newsData = news;
            return cell;
        }
        case 2:
            //问吧
            if([news.f_type intValue]==1) {
                //问吧专题
                ZhuanTiCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZhuanTiCell"];
                cell.newsData = news;
                return cell;
            }else{
                //问吧普通cell
                NewsQuestionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsQuestionCell"];
                cell.newsData = news;
                //cell.newsQuestionCellDelegate=self;
                return cell;
            }
        case 3: {
            //视频
            VideoShowCell *cell = [tableView dequeueReusableCellWithIdentifier:@"VideoShowCell"];
            cell.newsData = news;
            return cell;
        }
        default: {
            
            //广告
            if (news.f_commentsUrl && [news.f_commentsUrl rangeOfString:@"type=adv"].location != NSNotFound) {
                NewsCTCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCTCell"];
                cell.newsData = news;
                return cell;
            }
            
            //6大列表类型
            if ([news.f_newsType isEqualToString:@"doc"]) {
                NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell"];
                cell.newsData = news;
                return cell;
            }
            
            if ([news.f_newsType isEqualToString:@"zt"]) {
                NewsZTCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsZTCell"];
                cell.newsData = news;
                return cell;
            }
            
            if ([news.f_newsType isEqualToString:@"slide"]) {
                NewsImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsImageCell"];
                cell.newsData = news;
                return cell;
            }
            
            if([news.f_newsType isEqualToString:@"word"]) {
                NewsWordCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsWordCell"];
                cell.newsData = news;
                return cell;
            }
            
            if([news.f_newsType isEqualToString:@"dt"]) {
                NewsDTCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsDTCell"];
                cell.newsData = news;
                return cell;
            }
            
            if([news.f_newsType isEqualToString:@"ct"]) {
                NewsCTCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCTCell"];
                cell.newsData = news;
                return cell;
            }

            //未找到类型，待定
            NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell"];
            cell.newsData = news;
            return cell;
        }
    }
    
}

+ (CGFloat)heightForNewsCell:(M_News *)news whos:(NSInteger)whos {
    
    if (whos == 1 || whos== 2) {
        //特殊新闻
        return 251.0f;
    }
    
    // 视频
    if (whos == 3) {
        return 260.0f;
    }
    
    //广告
    if (news.f_commentsUrl && [news.f_commentsUrl rangeOfString:@"type=adv"].location != NSNotFound) {
        return 100.0f;
    }
        
    //6大列表类型
    NSString *newsType = news.f_type;
    if (!newsType || ![newsType length]) {
        newsType = news.f_newsType;
    }
    
    if ([newsType isEqualToString:@"doc"]) {
        return 100.0f;
    }
    
    if ([newsType isEqualToString:@"zt"]) {
        return 100.0f;
    }

    if([newsType isEqualToString:@"slide"]) {
        return 155.0f;
    }
    
    if([newsType isEqualToString:@"word"]) {
        return 50.0f;
    }
    
    if([newsType isEqualToString:@"dt"]) {
        return 200.0f;
    }
    
    if([newsType isEqualToString:@"ct"]) {
        return 100.0f;
    }
    
    //未找到类型，待定
    return 0;
}


+ (void)jumpToNewsDetail:(M_News *)news_ wohs:(NSInteger)wohs_ handle:(UIViewController *)handle_
{
    //保存阅读记录
    [[NewCellManager shared] saveReadHistory:news_.f_id];
    
    // 浏览新闻，增加积分
    [ServiceUserNew doAddScore:AddScoreType_News
                       success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {}
                       failure:^(NSString * _Nonnull message) {}];
    
    if (wohs_ == 2) {
        if([news_.f_type isEqualToString:@"1"]) {
            //去问吧专题界面
            //专题
            WenBaTagListController *controller = [WenBaTagListController new];
            controller.hidesBottomBarWhenPushed = YES;
            controller.subURL =news_.f_url;
            [handle_ showViewController:controller sender:nil];
        } else {
            //问吧详情
            WenBaDetailController *controller = [WenBaDetailController new];
            controller.hidesBottomBarWhenPushed = YES;
            controller.subURL=news_.f_url;
            [handle_ showViewController:controller sender:nil];
        }
    } else {
        
        //增加浏览量
        [ServiceNews doSendRead:news_.f_id success:nil failure:nil];
        
        //3种跳转方式
        if ([news_.f_type isEqualToString:@"slide"]) {
            //图集
            NewsAlbumViewController *controller = [NewsAlbumViewController new];
            controller.hidesBottomBarWhenPushed = YES;
            controller.urlString = news_.f_url;
            controller.f_thumbnail = news_.f_thumbnail;
            [handle_ showViewController:controller sender:nil];

        }
        else if([news_.f_type isEqualToString:@"doc"]) {
            
            NSString *commentsUrl = news_.f_commentsUrl;
            if (!commentsUrl) {
                commentsUrl = @" ";
            }
            
            if ([commentsUrl rangeOfString:@"type=forward"].location != NSNotFound) {
                //外链新闻
                NewsWebViewController *controller = [NewsWebViewController new];
                controller.hidesBottomBarWhenPushed = YES;
                controller.urlString = commentsUrl;
                controller.imgUrlString = news_.f_thumbnail;
                controller.titleString = news_.f_title;
                if ([commentsUrl rangeOfString:@"share=true"].location != NSNotFound)
                {
                    controller.hasShare = YES;
                }
                [handle_ showViewController:controller sender:nil];
            }
            else if ([commentsUrl rangeOfString:@"type=adv"].location != NSNotFound) {
                //广告
                NewsWebViewController *controller = [NewsWebViewController new];
                controller.hidesBottomBarWhenPushed = YES;
                controller.urlString = commentsUrl;
                controller.imgUrlString = news_.f_thumbnail;
                controller.titleString = news_.f_title;
                if ([commentsUrl rangeOfString:@"share=true"].location != NSNotFound)
                {
                    controller.hasShare = YES;
                }
                [handle_ showViewController:controller sender:nil];
            }
            else if ([commentsUrl rangeOfString:@"type=zt"].location != NSNotFound) {
                //专题链接形式
                NewsWebViewController *controller = [NewsWebViewController new];
                controller.hidesBottomBarWhenPushed = YES;
                controller.urlString = commentsUrl;
                controller.imgUrlString = news_.f_thumbnail;
                controller.titleString = news_.f_title;
                if ([commentsUrl rangeOfString:@"share=true"].location != NSNotFound)
                {
                    controller.hasShare = YES;
                }
                [handle_ showViewController:controller sender:nil];
            }
            else if ([commentsUrl rangeOfString:@"specialid="].location != NSNotFound) {
                //专题
                SpecialNewsListViewController *controller = [SpecialNewsListViewController new];
                controller.hidesBottomBarWhenPushed = YES;
                controller.sharethumb=news_.f_thumbnail;
                controller.sharetitle=news_.f_title;
                controller.subURL = [NSString stringWithFormat:@"%@&%@",URL_SUB_GET_SPECIAL_NEWS,[[commentsUrl componentsSeparatedByString:@"?"] lastObject]];
                [handle_ showViewController:controller sender:nil];
            }
            else if ([commentsUrl rangeOfString:@"type=live"].location != NSNotFound) {
                //视频直播
                if(news_==nil) {
                    return;
                }
                
                NSString *subURL=@"http://www3.ctdsb.net/index.php?m=live&c=index&a=index";
                
                NSString *playID = nil;
                playID = [NewCellManager paramValueOfUrl:commentsUrl withParam:@"lid"];
                if(playID==nil) {
                    [handle_ showHUDText:@"新闻信息已失效或不是视频新闻"];
                    return;
                }
                
                [ServiceNews doPlayNewsDetail:subURL lid:playID type:@"live" success:^(id responseObject, NSString *message) {
                    M_PlayNewsDetail *playdetail = responseObject;
                    [NewCellManager loginRongCloud:news_ play:playdetail handle:handle_];
                } failure:^(NSString *message) {
                    [handle_ showHUDText:@"新闻信息已失效或不是视频新闻"];
                }];
            }
            else {
                //普通新闻详情，需要请求详情，拼接HTML
                NewsDetailViewController *controller = [NewsDetailViewController new];
                controller.hidesBottomBarWhenPushed = YES;
                controller.urlString = [NSString stringWithFormat:@"%@&aid=%@",URL_SUB_GET_NEWS_DETAIL,news_.f_id];
                controller.f_thumbnail = news_.f_thumbnail;
                [handle_ showViewController:controller sender:nil];
            }
        }
        else {
            //待定
        }
    }
    
}


/**
 *登录融云，这里只是为了演示所以直接调融云的server接口获取token来登录，为了您的app安全，这里建议您通过你们自己的服务端来获取token。
 *
 */
+ (void)loginRongCloud:(M_News *)news_ play:(M_PlayNewsDetail *) play_ handle:(UIViewController *)handle_
{
    NSString *videoUrl = play_.f_rtmp;
    
    NSString *userId = nil;
    NSString *userName = nil;
    NSString *userProtrait = @"";
    
    
    NSString *url = @"http://www3.ctdsb.net/index.php?m=live&c=rongyun&a=token";
    
    AFHTTPSessionManager *mgr = [ServiceUtils commonHTTPManager];
    long timestamp = (long)[[NSDate date] timeIntervalSince1970];
    __weak __typeof(&*self)weakSelf = self;
    
    // 2.拼接请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    if ([AccountManager sharedAccountManager].f_isLogined) {
        userId =[AccountManager sharedAccountManager].f_uid;
        userProtrait =[AccountManager sharedAccountManager].f_user_img;
        userName =[AccountManager sharedAccountManager].f_nickname;
    }else {
        userId = [NSString stringWithFormat:@"u%ld",timestamp];
        userProtrait =@"";
        userName =@"匿名网友";
        [handle_ showHUDText:@"未登录也可看直播新闻"];
    }
    parameters[@"userId"]= userId;
    parameters[@"name"]= userName;
    parameters[@"portraitUri"]= userProtrait;
    
    [mgr POST:url parameters:parameters progress:nil
      success:^(NSURLSessionDataTask * _Nonnull task, id responseObject) {
          NSLog(@"loginRongCloud OK");
          NSNumber *code = responseObject[@"code"];
          if (code.intValue == 200) {
              NSString *token = responseObject[@"token"];
              NSString *userId = responseObject[@"userId"];
              
              [[RCDLive sharedRCDLive] connectRongCloudWithToken:token success:^(NSString *loginUserId) {
                  dispatch_async(dispatch_get_main_queue(), ^{
                      RCUserInfo *playuser = [[RCUserInfo alloc] init];
                      playuser.userId = userId;
                      playuser.portraitUri = userProtrait;
                      playuser.name=userName;
                      [RCIMClient sharedRCIMClient].currentUserInfo=playuser;
                      if([play_.f_orient_type isEqualToString:@"1"]) {
                          //横屏--视频区域为横屏
                          RCDLiveChatRoomLSViewController *chatRoomVC = [[RCDLiveChatRoomLSViewController alloc]init];
                          chatRoomVC.conversationType = ConversationType_CHATROOM;
                          chatRoomVC.targetId = play_.f_id;
                          chatRoomVC.targetName = play_.f_title;
                          chatRoomVC.contentURL = videoUrl;
                          //@"rtmp://live.hkstv.hk.lxdns.com/live/hks";
                          chatRoomVC.shareUrl = play_.f_url  ;//news_.f_url;
                          chatRoomVC.shareImg = news_.f_thumbnail;
                          chatRoomVC.shareContent = news_.f_source;
                          chatRoomVC.isScreenVertical = NO;//竖屏
                          chatRoomVC.playDetail = play_;
                          
                          chatRoomVC.hidesBottomBarWhenPushed = YES;
                          [handle_.navigationController setNavigationBarHidden:YES];
                          [handle_.navigationController pushViewController:chatRoomVC animated:NO];
                      }else {
                          //竖屏--视频竖屏全屏
                          RCDLiveChatRoomViewController *chatRoomVC = [[RCDLiveChatRoomViewController alloc]init];
                          chatRoomVC.conversationType = ConversationType_CHATROOM;
                          chatRoomVC.targetId = play_.f_id;
                          chatRoomVC.targetName = play_.f_title;
                          chatRoomVC.contentURL = videoUrl;
                          //@"rtmp://live.hkstv.hk.lxdns.com/live/hks";
                          //
                          chatRoomVC.shareUrl = play_.f_url;// news_.f_url;
                          chatRoomVC.isScreenVertical = NO;//竖屏
                          chatRoomVC.playDetail = play_;
                          chatRoomVC.hidesBottomBarWhenPushed = YES;
                          [[UIApplication sharedApplication] setStatusBarHidden:TRUE];
                          [handle_.navigationController setNavigationBarHidden:YES];
                          [handle_.navigationController pushViewController:chatRoomVC animated:NO];
                      }
                  });
              } error:^(RCConnectErrorCode status) {
                  dispatch_async(dispatch_get_main_queue(), ^{
                  });
                  
              } tokenIncorrect:^{
                  dispatch_async(dispatch_get_main_queue(), ^{
                      
                  });
              }];
              
              dispatch_async(dispatch_get_main_queue(), ^{
                  [MBProgressHUD hideHUDForView:handle_.view animated:YES];
              });
              
          } else {
              dispatch_async(dispatch_get_main_queue(), ^{
                  [MBProgressHUD hideHUDForView:handle_.view animated:YES];
                  
              });
          }
      } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
          //         NSLog( @"出错了");
          dispatch_async(dispatch_get_main_queue(), ^{
              [MBProgressHUD hideHUDForView:handle_.view animated:YES];
          });
          
      }];
}


+ (NSString *) paramValueOfUrl:(NSString *) url withParam:(NSString *) param {
    NSError *error;
    NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)",param];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    // 执行匹配的过程
    NSArray *matches = [regex matchesInString:url
                                      options:0
                                        range:NSMakeRange(0, [url length])];
    for (NSTextCheckingResult *match in matches) {
        NSString *tagValue = [url substringWithRange:[match rangeAtIndex:2]];  // 分组2所对应的串
        return tagValue;
    }
    return nil;
}

@end
